package com.shengqin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shengqin.common.pojo.CommonPage;
import com.shengqin.entity.SysOperLog;
import com.shengqin.entity.User;
import com.shengqin.mapper.SysOperaLogMapper;
import com.shengqin.service.ISysOperaLogService;
import com.shengqin.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class SysOperaLogServiceImpl extends ServiceImpl<SysOperaLogMapper,SysOperLog> implements ISysOperaLogService {
    @Autowired
    private IUserService userService;

    @Override
    public Page<SysOperLog> queryPage(CommonPage<SysOperLog> commonPage) {
        QueryWrapper<SysOperLog> wrapper = new QueryWrapper<>();
        SysOperLog queryParam = commonPage.getQueryParam();
        if (StringUtils.hasLength(queryParam.getOperName())) {
            wrapper.lambda().like(SysOperLog::getOperName, queryParam.getOperName());
        }
        if (StringUtils.hasLength(queryParam.getTitle())) {
            wrapper.lambda().like(SysOperLog::getTitle, queryParam.getTitle());
        }
        if (StringUtils.hasLength(queryParam.getBusinessType())) {
            wrapper.lambda().eq(SysOperLog::getBusinessType, queryParam.getBusinessType());
        }
        wrapper.lambda().orderByDesc(SysOperLog::getId);
        Page<SysOperLog> page = new Page<>(commonPage.getPageNo(), commonPage.getPageSize());
        page(page, wrapper);
        buildRecords(page.getRecords());
        return page;
    }

    private void buildRecords(List<SysOperLog> records) {
        if (!CollectionUtils.isEmpty(records)) {
            Set<String> recordUserIds = records.stream().map(SysOperLog::getOperName).collect(Collectors.toSet());
            if(!CollectionUtils.isEmpty(recordUserIds)){
                List<User> users = userService.listByIds(recordUserIds);
                records.forEach(record -> {
                    users.forEach(user -> {
                        if (record.getOperName().equals(user.getId().toString())) {
                            record.setOperRecordName(user.getAccount());
                        }
                    });
                });
            }
        }
    }
}
